using System;
using System.Collections.Generic;
using System.Text;
using System.Collections.ObjectModel;
using System.IO;
using System.Text.RegularExpressions;

namespace LocalizeMe.ResourceTool.VSTools
{
	internal class VSSolution
	{
		private Collection<VSProject> _projects;
		private string _name;
		private string _filepath;

		public VSSolution(string solutionFilePath)
		{
			_filepath = solutionFilePath;
			Regex reg = new Regex("(?<SolutionName>[^\\\\]*)\\.sln");

			Match match = reg.Match(solutionFilePath);
			if (match.Groups["SolutionName"].Success)
				this._name = match.Groups["SolutionName"].Value;
		}

		public string Name
		{
			get
			{
				return _name;
			}
		}

		public string FilePath
		{
			get
			{
				return _filepath;
			}
		}

		public Collection<VSProject> Projects
		{
			get
			{
				if (_projects == null)
					_projects = new Collection<VSProject>();
				return _projects;
			}
			set
			{
				_projects = value;
			}
		}

		private VSSolution AnalyseFile()
		{
			if (string.IsNullOrEmpty(this.FilePath))
				return this;

			StreamReader sr = new StreamReader(this.FilePath);
			try
			{
				string solContent = sr.ReadToEnd();
				if (string.IsNullOrEmpty(solContent))
					return null;

				return GetProjects(solContent);

			}
			catch (IOException ioex)
			{
			}
			catch (OutOfMemoryException outmemex)
			{
			}
			finally
			{
				sr.Dispose();
				
			}
			return this;
		}

		private VSSolution GetProjects(string content)
		{
			Regex reg = new Regex("Project\\(\"{([A-Z0-9]*-?)*}\"\\)\\s=\\s\"(?<ProjectName>([a-zA-Z0-9]*\\.?)*)\",\\s\"(?<ProjectFile>([a-zA-Z0-9]*\\\\?\\.?)*)\"");
			MatchCollection col = reg.Matches(content);
			foreach (Match match in col)
			{
				if (match.Groups["ProjectName"].Success && match.Groups["ProjectFile"].Success)
				{
					string projectName=match.Groups["ProjectName"].Value;
					string projectFile=match.Groups["ProjectFile"].Value;
					if (!File.Exists(projectFile))
					{
						FileInfo fi = new FileInfo(this.FilePath);
						projectFile = Path.Combine(fi.DirectoryName, projectFile);
					}

					if (File.Exists(projectFile))
					{
						VSProject proj = new VSProject(projectName, projectFile);
						proj.AnalyzeFile();
						this.Projects.Add(proj);
					}
				}

			}
			return this;
		}

		

		public static VSSolution GetVSSolution(string solutionFilePath)
		{
			if (string.IsNullOrEmpty(solutionFilePath))
				return null;

			VSSolution sol = new VSSolution(solutionFilePath);
			return sol.AnalyseFile();
			
		}
	}
}
